<?php

class Nuo_Menu_Render_Default
{
	/**
	 * @return html
	 */
	public function renderItem($item, $level, $sub)
	{
		$cls = (isset($item['extra']['li']) && isset($item['extra']['li']['class'])) ? $item['extra']['li']['class'] : '';

		$item['extra']['li']['class'] = 'lv' . $level . ' ' . $cls;

		if ($item['type'] == 'html')
		{
			return sprintf('<li %s>%s%s</li>', flat_html($item['extra']['li']), $item['html'], $sub);
		}
		else
		if ($item['type'] == 'url')
		{

			$url = Nuo::getUrl($item['url']);
		}
		else
		{
			$url = $item['url'];
		}

		$pattern = '<li %s><a href="%s" %s><span>%s</span></a>%s</li>';
		return sprintf($pattern, flat_html($item['extra']['li']), $url, flat_html($item['extra']['a']), __text($item['label']), $sub);
	}

	/**
	 * @return string
	 */
	public function render($items, $level, $extra = array())
	{
		if (empty($items))
		{
			return '';
		}

		$xhtml = array();

		$clearfix = isset($extra['clearfix']) ? $extra['clearfix'] : false;

		foreach ($items as $item)
		{
			try
			{
				if (isset($item['type']))
				{
					if ($item['type'] == 'plugin' && $item['plugin'])
					{
						list($plugin, $method) = explode(':', $item['plugin']);
						$obj = Nuo::getPlugin($plugin);
						if ($obj && method_exists($obj, $method))
						{
							$item = $obj -> {$method}($item, $level, $this);
						}
						else
						{
							$item = NULL;
						}
					}
				}

				if (null == $item)
				{
					continue;
				}

				$sub = '';

				if (isset($item['items']) && $item['items'])
				{
					$sub = $this -> render($item['items'], $level + 1, $item['extra']['ul']);
				}

				$xhtml[] = $this -> renderItem($item, $level, $sub);

			}
			catch(Exception $e)
			{
				Nuo_Log::instance()->write(Nuo::ERROR, $e -> getMessage());
			}
		}

		$xhtml = sprintf('<ul %s>%s</ul>', flat_html($extra), implode(PHP_EOL, $xhtml));

		if ($level == 0 AND $clearfix)
		{
			$xhtml .= '<div class="clearfix"></div>';
		}
		return $xhtml;
	}

}
